var _ = require('lodash');
var appContext = require('../../../config/app.context');
var io = require('socket.io-client');

payController.$inject = ['$scope', '$rootScope', '$location', 'cartService', 'addrService', 'orderService'];

function payController($scope, $rootScope, $location, cartService, addrService, orderService) {
    // alert(11111111);
    var socketConfig = {
        path:"/O2OMerchant/api/"+'socketio'
    }
    var socket = io.connect('http://10.222.29.186:8080',socketConfig);

    // socket.emit('order','Hello');
    // socket.on('order',function(msg){
    //     alert(msg);
    // });
    // console.log('2222222222222');

    /**
     * get current merchant info
     */
    var currentMerchantJson = window.sessionStorage.getItem('currentMerchant');
    if (!currentMerchantJson) {
        alert('No merchant info found!');
        window.history.back();
        return;
    }
    $scope.currentMerchant = JSON.parse(currentMerchantJson);


    /**
     * cart management
     */
    $rootScope.$on('loginedCustomer', function() {
        if ($rootScope.globalData.loginedCustomer) {
            $scope.cart = cartService.getCart($rootScope.globalData.loginedCustomer._id);
        }

        $scope.getTotalPrice = function() {
            return cartService.getTotalPrice($rootScope.globalData.loginedCustomer._id);
        }
    });


    /**
     * address management
     */
    $scope.addrs = [];
    /**
     * wait until customer id is got
     */
    $rootScope.$on('loginedCustomer', function() {
        if ($rootScope.globalData.loginedCustomer) {
            // $scope.addrs = $rootScope.globalData.loginedCustomer.address;
            addrService.getAddressListByCustomerId($rootScope.globalData.loginedCustomer._id).then(
                function(response) {
                    // console.log(response.data);
                    if (response.data.result) {
                        $scope.addrs = response.data.data.address;
                    }
                },
                function(err) {
                    console.log(err.data);
                }
            );
        }
    });

    $scope.addAddress = function() {
        if (!$scope.newAddr || !$scope.newAddr.address) {
            console.log('address empty!');
            return;
        }
        $scope.newAddr.customerId = $rootScope.globalData.loginedCustomer._id;
        addrService.addAddress($scope.newAddr).then(
            function(response) {
                if (response.data.result) {
                    // console.log('address add success!');
                    $scope.addrs.push({_id: response.data.data, name: $scope.newAddr.address});
                    $scope.newAddr.address = '';
                }
            },
            function(err) {
                console.log(err.data);
            }
        );
    }

    $scope.deleteAddress = function(addrId) {
        addrService.removeAddress($rootScope.globalData.loginedCustomer._id, addrId).then(
            function(response) {
                // console.log('delete address success');
                $scope.addrs = $scope.addrs.filter(function(addr) {
                    return addr._id != addrId;
                });
            },
            function(err) {
                console.log(err.data);
            }
        );
    }


    /**
     * order management - pay
     */
    var paySuccessModal = $('#o2oc-pay-panel #pay-success-modal');
    $scope.payOrder = function() {
        if (!$scope.cart) {
            return;
        }

        console.log('6666');
        socket.emit('orderFromClient','new order');
        console.log($scope.newOrder);
        
        // console.log($scope.cart);
        $scope.newOrder.createTime = new Date();
        $scope.newOrder.status = 0;
        $scope.newOrder.totalPrice = cartService.getTotalPrice($rootScope.globalData.loginedCustomer._id);
        $scope.newOrder.orderItem = [];
        $scope.cart.forEach(function(cartItem) {
            var itemClone = _.clone(cartItem);
            delete itemClone._id;
            delete itemClone.img;
            delete itemClone.$$hashKey;
            $scope.newOrder.orderItem.push(itemClone);
        });
        $scope.newOrder.customer = $rootScope.globalData.loginedCustomer._id;
        $scope.newOrder.merchant = $scope.currentMerchant._id;

        console.log($scope.newOrder);

        orderService.addOrder($scope.newOrder).then(
            function(response) {
                if (response.data.result) {
                    paySuccessModal.modal('show');
                }
            },
            function(err) {
                console.log(err.data);
            }
        );
    }

    paySuccessModal.on("hidden.bs.modal", function() {
        cartService.setCart($rootScope.globalData.loginedCustomer._id, []);
        $rootScope.$apply(function() {
            $location.path(appContext.path + '/auth/orders');
        });
    });
}

module.exports = payController;